import { webContents } from '@electron/remote'
import { ShallowRef } from 'vue'

let inited = false

// webview标签的ref
const webviewDoms: {
    webview: Electron.WebviewTag | null
    devtools: Electron.WebviewTag | null
} = {
    webview: null,
    devtools: null
}
// webbiew加载完成之后保存它的webContents对象
const webContent: Record<keyof typeof webviewDoms, Electron.WebContents | undefined> = {
    webview: undefined,
    devtools: undefined
}

// 获取webview标签的dom
export const getWebviewDom = (key: keyof typeof webviewDoms) => {
    return webviewDoms[key]
}

// 获取webContents
export const getWebContent = (key: keyof typeof webContent) => {
    return webContent[key]
}

// webbiew加载完成之后保存它的webContents对象
const handleDomReady = (key: keyof typeof webContent) => {
    if (!webviewDoms[key]) {
        return
    }
    const dom = webviewDoms[key]
    const webContentId = dom.getWebContentsId()
    webContent[key] = webContents.fromId(webContentId)
}

export const initWebviewRefs = async (
    webviewRefs: {
        webview: Readonly<ShallowRef<Electron.WebviewTag | null>>
        devtools: Readonly<ShallowRef<Electron.WebviewTag | null>>
    },
    config?: {
        onBackgroundImageSelected?: (message: string) => void
    }
) => {
    if (inited || !webviewRefs.devtools.value || !webviewRefs.webview.value) return
    inited = true
    // 保存dom
    webviewDoms.webview = webviewRefs.webview.value
    webviewDoms.devtools = webviewRefs.devtools.value
    // 开始处理
    const keys = Object.keys(webviewRefs) as (keyof typeof webviewRefs)[]
    const proms: Promise<void>[] = []
    // 两个webview内容加载完成后吧webContents对象保存起来
    keys.forEach((key) => {
        proms.push(
            new Promise((resolve) => {
                webviewRefs[key].value?.addEventListener('dom-ready', () => {
                    handleDomReady(key)
                    resolve()
                })
            })
        )
    })
    // 两个webview都准备好
    await Promise.all(proms)
    if (!webContent.devtools || !webContent.webview) return
    // devtools显示在右边的webview里面
    webContent.webview.setDevToolsWebContents(webContent.devtools)

    // 默认打开devtools start
    webContent.webview.openDevTools({ mode: 'undocked' })
    webContent.devtools.executeJavaScript('window.location.reload()')
    // 默认打开devtools end

    // 每次发生加载完成事件后往window里注入onSelectionChanged监听器，选中元素变化时触发
    webviewRefs.webview.value?.addEventListener('did-finish-load', () => {
        console.log('webview did-finish-load')
        // 声明onSelectionChanged函数，此函数会被devtools插件在选中元素时调用
        webContent.webview?.executeJavaScript(`
window.onSelectionChanged = () => {
    const el = $0
    const backgroundImage = getComputedStyle(el).backgroundImage
    let src = backgroundImage
    // 是img元素吗
    console.log(el.src)
    if (el.tagName === 'IMG') {
            src = el.src
    }
    console.log('BACKGROUND_IMAGE ' + src)
}
        `)
    })

    // 监听webview的console消息
    webviewRefs.webview.value?.addEventListener('console-message', (e) => {
        console.log('console-message')
        if (e.message.startsWith('BACKGROUND_IMAGE ')) {
            const message = e.message.replace('BACKGROUND_IMAGE ', '')
            config?.onBackgroundImageSelected && config?.onBackgroundImageSelected(message)
        }
    })
}
